﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using UnisysMassiveImporter_v2.Entidades.Mensajes;
using UnisysMassiveImporter_v2.Entidades.Documentos;
using UnisysMassiveImporter_v2.Entidades.Configuracion;

namespace UnisysMassiveImporter_v2.Negocio.Archivos
{
    public class Manipulacion_Archivos
    {
        
        private Datos.Archivos.Files files=new Datos.Archivos.Files();


        #region Obtener DATA
        public ArrayList getDataPreview(ref Configuration appConfig,ref Thread_Config threadConfig)
        {
            switch (threadConfig.DirectoryOrganization)
            {
                case 1:
                    {
                        try
                        {
                            ArrayList expedientes = files.getDataPreview1(ref appConfig,ref threadConfig);
                            return expedientes;
                        }
                        catch (Exception e)
                        {
                            throw new Exception("Error Message: " + e.Message);
                        }
                    }
                case 2:
                    {
                        try
                        {
                            ArrayList expedientes = files.getDataPreview2(ref appConfig, ref threadConfig);
                            return expedientes;
                        }
                        catch (Exception e)
                        {
                            throw new Exception("Error Message: " + e.Message);
                        }
                    }

                case 3:
                    {
                        try
                        {
                            ArrayList expedientes = files.getDataPreview3(ref appConfig, ref threadConfig);
                            return expedientes;
                        }
                        catch (Exception e)
                        {
                            throw new Exception(e.Message);
                        }
                    }
                default:
                    throw new Exception("Tipo de Directorio Invalido");
            }
        }
        #endregion

        #region Obtener Images
        public void getImages(Document document, ref Configuration appConfig, ref Thread_Config threadConfig)
        {
            
            InfoMessage message = new InfoMessage();
            message.sendMessage("Iniciando la creacion del images previewList", InfoMessage.Information_Message, 573, threadConfig.Name,ref appConfig);
            switch (threadConfig.DirectoryOrganization)
            {
                case 1:
                    {
                        for (int i = 0; i < document.indexFields.Count; i++)
                        {
                            IndexField indexField = (IndexField)document.indexFields[i];
                            if (indexField.name.Equals("IMAGEN"))
                                try
                                {
                                    message.sendMessage("Imagen: " + indexField.value + " encontrada en los datos de indexacion", InfoMessage.Information_Message, 583, threadConfig.Name, ref appConfig);
                                    Images image = new Images();
                                    image.name = indexField.value;
                                    image.path = files.getImages1(indexField.value,ref appConfig, ref threadConfig);
                                    document.images.Add(image);
                                }
                                catch (Exception e) { throw new Exception(e.Message); }
                            
                        }
                        return; 
                    }
                case 2:
                    {
                        for (int i = 0; i < document.indexFields.Count; i++)
                        {
                            IndexField indexField = (IndexField)document.indexFields[i];
                            if (indexField.name.Equals("IMAGEN"))
                                try
                                {
                                    message.sendMessage("Buscando imagen: " + indexField.value + " encontrada en los datos de indexacion", InfoMessage.Information_Message, 583, threadConfig.Name,ref appConfig);
                                    Images image = new Images();
                                    image.name = indexField.value;
                                    image.path = files.getImages2(indexField.value,ref appConfig,ref threadConfig);
                                    document.images.Add(image);
                                }
                                catch (Exception e) { throw new Exception(e.Message); }
                        }
                        return;
                    }
                case 3:
                    {
                        
                            try
                            {
                                message.sendMessage("Buscando imagenes en la carpeta: "+new System.IO.FileInfo(document.filePath).DirectoryName, InfoMessage.Information_Message, 583, threadConfig.Name,ref appConfig);
                                ArrayList temp = files.getImages3(document,ref appConfig,ref threadConfig);
                                for (int i = 0; i < temp.Count; i++)
                                {
                                    Images image = (Images)temp[i];
                                    document.images.Add(image);
                                }
                            }
                            catch (Exception e) { throw new Exception(e.Message); }
                        
                        return;
                    }
                default:
                    {
                       throw new Exception("Parametro de DirectoryOrganization no esta bien configurado Thread: Name. Valor Actual: " + threadConfig.DirectoryOrganization.ToString());                       
                    }
            }
        }
    #endregion

        #region Procesar Archivos
        private MailMessage generateStadistics(MailMessage totalResult,MailMessage parcialResult){
            totalResult.files++;
            totalResult.documentsNoOk += parcialResult.documentsNoOk;
            totalResult.documentsOk += parcialResult.documentsOk;
            return totalResult;
        }

        public MailMessage createDocuments(ArrayList documents, ref Configuration appConfig, ref Thread_Config threadConfig)
        {
            MailMessage result = new MailMessage();
            InfoMessage message = new InfoMessage();
            switch (threadConfig.Filetype)
            {
                case 1:
                    {
                        for (int i = 0; i < documents.Count; i++)
                        {                            
                            Document document = (Document)documents[i];
                            message.sendMessage("Procesando Archivo: " + document.filePath, InfoMessage.Information_Message, 547, threadConfig.Name, ref appConfig);

                            try
                            {
                                MailMessage parcialResult = files.procesarXML(document, ref appConfig,ref threadConfig);                                
                                result=generateStadistics(result,parcialResult);
                                if (parcialResult.documentsNoOk > 0)
                                    this.errorDataHistory(document,ref appConfig,ref threadConfig);
                                message.sendMessage("Archivo Procesado con exito: " + document.filePath, InfoMessage.Success_Message, 278, threadConfig.Name, ref appConfig);  
                            }
                            catch (Exception e)
                            {
                                FileMessage fMessage = new FileMessage("El archivo " + document.filePath + " no fue bien indexado. Revisar Bitacoras.", e, document.filePath, 105,  threadConfig.Name);
                                fMessage.sendMessage( ref appConfig);
                                result.files++;
                                this.errorDataHistory(document, ref appConfig, ref threadConfig);              
                                continue;
                            }
                        }
                        return result;
                    }
                case 2:
                    {
                        for (int i = 0; i < documents.Count; i++)
                        {
                            
                            Document document = (Document)documents[i];
                            message.sendMessage("Procesando Archivo: " + document.filePath, InfoMessage.Information_Message, 547, threadConfig.Name, ref appConfig);
                            try
                            {
                                MailMessage parcialResult = files.procesarCSV(document, ref appConfig,ref threadConfig);
                                result = generateStadistics(result, parcialResult);
                                if (parcialResult.documentsNoOk > 0)
                                    this.errorDataHistory(document, ref appConfig, ref threadConfig);

                                message.sendMessage("Archivo Procesado con exito: " + document.filePath, InfoMessage.Success_Message, 278, threadConfig.Name, ref appConfig);  
                            }
                            catch (Exception e)
                            {
                                FileMessage fMessage = new FileMessage("El archivo " + document.filePath + " no fue bien indexado. Revisar Bitacoras.", e, document.filePath, 105,  threadConfig.Name);
                                fMessage.sendMessage( ref appConfig);
                                result.files++;
                                this.errorDataHistory(document, ref appConfig, ref threadConfig);              
                                continue;
                            }
                        }
                        return result;
                    }

                case 3:
                    {
                        for (int i = 0; i < documents.Count; i++)
                        {
                            
                            Document document = (Document)documents[i];
                            message.sendMessage("Procesando Archivo: " + document.filePath, InfoMessage.Information_Message, 547, threadConfig.Name, ref appConfig);
                            try
                            {
                                MailMessage parcialResult = files.procesarPLANO(document, ref appConfig, ref threadConfig);
                                result = generateStadistics(result, parcialResult);
                                if (parcialResult.documentsNoOk > 0)
                                    this.errorDataHistory(document, ref appConfig, ref threadConfig);
                                message.sendMessage("Archivo Procesado con exito: " + document.filePath, InfoMessage.Success_Message, 278, threadConfig.Name, ref appConfig);  
                            }
                            catch (Exception e)
                            {
                                FileMessage fMessage = new FileMessage("El archivo " + document.filePath + " no fue bien indexado. Revisar Bitacoras.", e, document.filePath, 105, threadConfig.Name);
                                fMessage.sendMessage( ref appConfig);
                                result.files++;
                                this.errorDataHistory(document, ref appConfig, ref threadConfig);              
                                continue;
                            }
                        }
                        return result;
                    }
                default:
                    throw new Exception("Tipo de Archivo Invalido");
            }
        }
        #endregion

        #region Manipulacion Archivos

        public void historyDataGeneration(Document document, ref Configuration appConfig, ref Thread_Config threadConfig)
        {
            InfoMessage message = new InfoMessage();

            System.IO.FileInfo file = new System.IO.FileInfo(document.filePath);
            String historyDirectory = appConfig.fileSystemHistory + "\\" + DateTime.Now.ToString("yyyy'-'MM'-'dd")+"\\"+threadConfig.Name+"\\"+file.Name.Split('.')[0];
            try
            {
                message.sendMessage("Generando Historial: "+document.filePath, InfoMessage.Information_Message, 551, threadConfig.Name, ref appConfig);

                message.sendMessage("Carpeta History: " + historyDirectory, InfoMessage.Information_Message, 552, threadConfig.Name, ref appConfig);

                message.sendMessage("Moviendo Data: " + document.filePath + " a:" + historyDirectory, InfoMessage.Information_Message, 553, threadConfig.Name, ref appConfig);

                if (!(System.IO.Directory.Exists(historyDirectory)))
                {
                    message.sendMessage("Carpeta History: " + historyDirectory + " inexistente se procede a su creacion", InfoMessage.Information_Message, 554, threadConfig.Name, ref appConfig);
                    System.IO.Directory.CreateDirectory(historyDirectory);
                    message.sendMessage("Carpeta History: " + historyDirectory + " creada con exito", InfoMessage.Success_Message, 254, threadConfig.Name, ref appConfig);
                }
                files.Move(files.cambiandoExtension(document.filePath, ".hist", ref appConfig, ref threadConfig), historyDirectory, ref appConfig, ref threadConfig);
                    
            }
            catch (Exception e)
            {
                FileMessage fMessage=new FileMessage("Imposible generar historial", e, document.filePath, 106,threadConfig.Name);
                fMessage.sendMessage( ref appConfig);
            }                        
            

        }
        public void historyImagesGeneration(Document document, ref Configuration appConfig, ref Thread_Config threadConfig)
        {
            InfoMessage message = new InfoMessage();
            System.IO.FileInfo file = new System.IO.FileInfo(document.filePath);
            String historyDirectory = appConfig.fileSystemHistory + "\\" + DateTime.Now.ToString("yyyy'-'MM'-'dd") + "\\" + threadConfig.Name + "\\" + file.Name.Split('.')[0];
            try
            {
                for (int i = 0; i < document.images.Count; i++)
                {
                    Images image = (Images)document.images[i];
                    if (System.IO.File.Exists(image.path))
                    {
                        if (!(System.IO.Directory.Exists(historyDirectory)))
                        {
                            message.sendMessage("Carpeta History: " + historyDirectory + " inexistente se procede a su creacion", InfoMessage.Information_Message, 554, threadConfig.Name, ref appConfig);
                            System.IO.Directory.CreateDirectory(historyDirectory);
                            message.sendMessage("Carpeta History: " + historyDirectory + " creada con exito", InfoMessage.Success_Message, 254, threadConfig.Name, ref appConfig);
                        }
                        files.Move(files.cambiandoExtension(image.path, ".hist",ref appConfig,ref threadConfig), historyDirectory, ref appConfig,ref threadConfig);
                    }
                    else
                        continue;
                }
            }
            catch (Exception e)
            {
                FileMessage fMessage = new FileMessage("Imposible generar historial de imagenes", e, document.filePath, 106, threadConfig.Name);
                fMessage.sendMessage(ref appConfig);
            }
        }

        public void historyDataDelete(Document document, ref Configuration appConfig, ref Thread_Config threadConfig)
        {
            InfoMessage message = new InfoMessage();
            message.sendMessage("Eliminando el archivo: "+document.filePath, InfoMessage.Information_Message, 555, threadConfig.Name,ref appConfig);
           
            try
            {
                message.sendMessage("Intentando borrar archivo: " + document.filePath, InfoMessage.Information_Message, 556, threadConfig.Name, ref appConfig);
                files.Delete(files.cambiandoExtension(document.filePath, ".del", ref appConfig,ref threadConfig), ref appConfig, ref threadConfig);
                message.sendMessage("Archivo Borrado: " + document.filePath, InfoMessage.Success_Message, 270, threadConfig.Name, ref appConfig);
            }
            catch (Exception e)
            {
                FileMessage fMessage = new FileMessage("Imposible eliminar el archivo: " + document.filePath + " .Se procede a intentar cambiar las extenciones", e, document.filePath, 107, threadConfig.Name);
                fMessage.sendMessage( ref appConfig);
            }

            
            
        }
        public void historyImagesDelete(Document document, ref Configuration appConfig, ref Thread_Config threadConfig)
        {
            InfoMessage message = new InfoMessage();
            for (int i = 0; i < document.images.Count; i++)
            {
                Images image = (Images)document.images[i];
                if (System.IO.File.Exists(image.path))
                {
                    System.IO.FileInfo imageFile = new System.IO.FileInfo(image.path);
                    try
                    {
                        message.sendMessage("Intentando borrar archivo:: " + imageFile.FullName, InfoMessage.Information_Message, 556, threadConfig.Name, ref appConfig);
                        files.Delete(files.cambiandoExtension(imageFile.FullName, ".del", ref appConfig,ref threadConfig), ref appConfig, ref threadConfig);
                        message.sendMessage("Carpeta Borrada: " + imageFile.DirectoryName, InfoMessage.Success_Message, 270, threadConfig.Name, ref appConfig);
                    }
                    catch (Exception e)
                    {
                        FileMessage fMessage = new FileMessage("Imposible eliminar el archivo: " + imageFile.FullName + " .Se procede a intentar cambiar las extenciones", e, document.filePath, 107, threadConfig.Name);
                        fMessage.sendMessage( ref appConfig);
                        continue;
                    }
                }
                else
                    continue;
            }
        }


        public void errorDataHistory(Document document, ref Configuration appConfig, ref Thread_Config threadConfig)
        {
            InfoMessage message = new InfoMessage();

            System.IO.FileInfo file = new System.IO.FileInfo(document.filePath);
            String errorDirectory = appConfig.fileSystemError + "\\" + DateTime.Now.ToString("yyyy'-'MM'-'dd") + "\\" + threadConfig.Name + "\\" + file.Name.Split('.')[0];
            try
            {

                message.sendMessage("Carpeta Error: " + errorDirectory, InfoMessage.Information_Message, 552, threadConfig.Name, ref appConfig);

                message.sendMessage("Moviendo Data: " + document.filePath + " a:" + errorDirectory, InfoMessage.Information_Message, 553, threadConfig.Name, ref appConfig);

                if (!(System.IO.Directory.Exists(errorDirectory)))
                {
                    message.sendMessage("Carpeta Error: " + errorDirectory + " inexistente se procede a su creacion", InfoMessage.Information_Message, 554, threadConfig.Name, ref appConfig);
                    System.IO.Directory.CreateDirectory(errorDirectory);
                    message.sendMessage("Carpeta Error: " + errorDirectory + " creada con exito", InfoMessage.Success_Message, 254, threadConfig.Name, ref appConfig);
                }
                files.Move(files.cambiandoExtension(document.filePath, ".err", ref appConfig,ref threadConfig), errorDirectory, ref appConfig, ref threadConfig);
                                
            }
            catch (Exception e)
            {
                FileMessage fMessage = new FileMessage("Imposible generar historial errores", e, document.filePath, 106, threadConfig.Name);
                fMessage.sendMessage( ref appConfig);
            }  
        }
        public void errorImagesHistory(Document document, ref Configuration appConfig, ref Thread_Config threadConfig)
        {
            InfoMessage message = new InfoMessage();
            System.IO.FileInfo file = new System.IO.FileInfo(document.filePath);
            String errorDirectory = appConfig.fileSystemError + "\\" + DateTime.Now.ToString("yyyy'-'MM'-'dd") + "\\" + threadConfig.Name + "\\" + file.Name.Split('.')[0];
            try
            {
                for (int i = 0; i < document.images.Count; i++)
                {
                    Images image = (Images)document.images[i];
                    if (System.IO.File.Exists(image.path))
                    {
                        if (!(System.IO.Directory.Exists(errorDirectory)))
                        {
                            message.sendMessage("Carpeta History: " + errorDirectory + " inexistente se procede a su creacion", InfoMessage.Information_Message, 554, threadConfig.Name, ref appConfig);
                            System.IO.Directory.CreateDirectory(errorDirectory);
                            message.sendMessage("Carpeta History: " + errorDirectory + " creada con exito", InfoMessage.Success_Message, 254, threadConfig.Name, ref appConfig);
                        }
                        files.Move(files.cambiandoExtension(image.path, ".err", ref appConfig,ref threadConfig), errorDirectory, ref appConfig, ref threadConfig);
                    }
                    else
                        continue;
                }
            }
            catch (Exception e)
            {
                FileMessage fMessage = new FileMessage("Imposible generar historial errores", e, document.filePath, 106,threadConfig.Name);
                fMessage.sendMessage( ref appConfig);
            }
        }

        #endregion
        public void printList(ArrayList list, ref Configuration appConfig,ref Thread_Config threadConfig)
        {
            InfoMessage message = new InfoMessage();
            message.sendMessage("Imprimiendo archivos data a procesar...", InfoMessage.Information_Message, 540, threadConfig.Name, ref appConfig);
            for (int i = 0; i < list.Count; i++)
            {
                Document file = (Document)list[i];
                message.sendMessage("Archivo  a procesar: " + file.filePath, InfoMessage.Information_Message, 541, threadConfig.Name, ref appConfig);
            }
            message.sendMessage("Fin de la impresion del data previewList...", InfoMessage.Information_Message, 542, threadConfig.Name, ref appConfig);
        }
    }
}
